package com.springboot.activemq.customer.demo.code;

import com.google.common.util.concurrent.ThreadFactoryBuilder;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.jms.config.DefaultJmsListenerContainerFactory;
import org.springframework.jms.config.JmsListenerContainerFactory;

import javax.jms.ConnectionFactory;
import java.util.concurrent.*;

/**
 * 为了同时支持topic和queue,增加此配置文件
 */
@Slf4j
@Configuration
public class ActiveConfig {

    private static ThreadFactory namedThreadFactory = new ThreadFactoryBuilder()
            .setNameFormat("activemq-pool-%d").setDaemon(true).build();
    private static ExecutorService pool;

    /**
     * 初始化连接池
     */
    static {
        if (pool == null) {
            pool = new ThreadPoolExecutor(6, 6,
                    0L, TimeUnit.MILLISECONDS,
                    new LinkedBlockingQueue<>(6), namedThreadFactory, new ThreadPoolExecutor.AbortPolicy());
        }
    }

    /**
     * 处理topic消息
     *
     * @param connectionFactory
     * @return
     */
    @Bean
    public JmsListenerContainerFactory<?> topicListenerFactory(ConnectionFactory connectionFactory) {
        DefaultJmsListenerContainerFactory factory = new DefaultJmsListenerContainerFactory();
        factory.setPubSubDomain(true);
        factory.setConnectionFactory(connectionFactory);
        factory.setTaskExecutor(pool);
        return factory;
    }

    /**
     * 处理queue消息
     *
     * @param connectionFactory
     * @return
     */
    @Bean
    public JmsListenerContainerFactory<?> queueListenerFactory(ConnectionFactory connectionFactory) {
        DefaultJmsListenerContainerFactory factory = new DefaultJmsListenerContainerFactory();
        factory.setPubSubDomain(false);
        factory.setConnectionFactory(connectionFactory);
        factory.setTaskExecutor(pool);
        return factory;
    }

}

